package cn.neusoft.service.impl;

import cn.neusoft.po.Order;
import cn.neusoft.po.Order;
import cn.neusoft.mapper.OrderMapper;
import cn.neusoft.query.OrderQuery;
import cn.neusoft.service.IOrderDetailService;
import cn.neusoft.service.IOrderService;
import cn.neusoft.util.CustomIdGenerator;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Date;

/**
 * @author hxj
 * @since 2024-01-02
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {

    @Autowired
    CustomIdGenerator customIdGenerator;

    @Autowired
    IOrderDetailService orderDetailService;

    @Transactional
    @Override
    public boolean addOrder(Order order) {

        //生成订单编号  用的雪花算法
        Long ordersn = customIdGenerator.nextId(order);
        order.setOrdersn(ordersn.toString());
        order.setLastconfirmtime(new Date());
        order.setLastpaytime(new Date());
        order.setState(1);

        //添加订单
        int insert = baseMapper.insert(order);
        if (insert>0){
            //循环给订单详情设置订单编号
            order.getOrderDetails().forEach(orderDetail -> {
                orderDetail.setOrdersn(order.getOrdersn());
            });
            //批量添加订单详情
            boolean b = orderDetailService.saveBatch(order.getOrderDetails());
            return b;
        }

        return false;
    }

    @Override
    public Page<Order> getByPage(OrderQuery query) {
        //存放搜索条件
        QueryWrapper<Order> queryWrapper = Wrappers.query(new Order())
                //StringUtils.hasText(query.getUsername())  StringUtils字符串工具类  判断变量是否有值
                //三个参数：该条件加不加 boolean值 ,  比对的字段名称(跟数据库一致) ,   比对的值
                .eq(query.getUserId()!=null,"user_id",query.getUserId())
                .eq(query.getOrderId()!=null,"order_id",query.getOrderId())
                .orderByDesc("id");

        //存放分页条件
        Page pageQuery = new Page(query.getCurrent(),query.getSize());

        //自定义分页时  准备好分页条件Page  准备好搜索条件Wrapper
        Page<Order> departmentIPage = baseMapper.selectJoin(pageQuery, queryWrapper);
        return departmentIPage;
    }
}
